import React, { useState, useEffect } from 'react';
import { Button, Drawer, Form, FormInstance } from 'antd';
import { Node } from '@antv/x6';
import SearchBase, { ItemProps } from '../SearchBase';
import { nextTick } from '../../tools';

interface CreateNodeProps {
  visible?: boolean;
  onClose: () => void;
  onSubmit?: (nodeData: any) => Promise<boolean>;
  node?: Node;
  onLoad?: (form: FormInstance) => void;
  rootNode?: false | string | HTMLElement | (() => HTMLElement);
}

const CreateNode: React.FC<CreateNodeProps> = function ({
  visible,
  onClose,
  onSubmit,
  onLoad,
  node,
  rootNode,
}) {
  const [form] = Form.useForm();
  const [items, setItems] = useState<ItemProps[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [FormItems, setFormItems] = useState<React.ReactNode>();
  useEffect(() => {
    onLoad && onLoad(form);
  }, []);

  useEffect(() => {
    if (!visible) return;
    setFormItems(undefined);
    setItems([]);
    if (node) {
      const { data } = node;
      const moduleProps = (window as any)._moduleProps || {};
      const { moduleType } = data;
      const moduleFormItems = moduleProps[moduleType];
      let modulePropItems: ItemProps[] | undefined;
      if (
        Object.prototype.toString.apply(moduleFormItems) === '[object Array]'
      ) {
        modulePropItems = moduleFormItems;
      } else if (
        Object.prototype.toString.apply(moduleFormItems) === '[object Function]'
      ) {
        const formItemResult = moduleFormItems(data, form);
        if (
          Object.prototype.toString.apply(formItemResult) === '[object Array]'
        ) {
          modulePropItems = formItemResult;
        } else if (
          Object.prototype.toString.apply(formItemResult) === '[object Object]'
        ) {
          setFormItems(formItemResult);
        }
      }
      if (modulePropItems) {
        const initValue = modulePropItems.reduce((p, c) => {
          p[c.name as string] = data[c.name as string];
          return p;
        }, {});
        setItems(modulePropItems);
        nextTick(() => form.setFieldsValue(initValue));
      }
    }
  }, [visible, node]);

  const submitForm = () => {
    form.validateFields().then(async (values: any) => {
      setLoading(true);
      if (onSubmit) {
        const copyNode = node!.clone();
        copyNode.setData(values);
        const ret = await onSubmit(copyNode);
        setLoading(false);
        if (ret) onClose();
      } else {
        setLoading(false);
        onClose();
      }
    });
  };

  return (
    <Drawer
      title={`${node?.data?.id ? '编辑' : '新建'}节点`}
      placement="right"
      className="ra-arch-createNode"
      closable={false}
      onClose={onClose}
      visible={visible}
      getContainer={rootNode}
      extra={
        <Button
          loading={loading}
          type="primary"
          ghost
          size="small"
          onClick={submitForm}
        >
          提交
        </Button>
      }
    >
      {FormItems ? FormItems : <SearchBase form={form} items={items} />}
    </Drawer>
  );
};

export default CreateNode;
